package com.awei.interceptors;


import com.awei.utils.JwtUtil;
import com.awei.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try {
            if (token == null) {
                throw new RuntimeException("token不能为空");
            }
            //2.解析token
            Map<String, Object> map = JwtUtil.parseToken(token);
            //3.从map中获取用户id
            Integer id = (Integer) map.get("id");
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            //http响应状态码为401
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
